import { useTaskStore } from '@/store'
import { PlusOutlined, ReloadOutlined, ClearOutlined } from '@ant-design/icons'
import { Button, Tooltip } from 'antd'
import { TASK_TYPE } from '@/enums'
import { prioritySortOptions, taskItemTypeConfig } from '../config'
import { useMemo, useCallback } from 'react'

export default function TaskActions(): React.JSX.Element {
  const prioritySort = useTaskStore((state) => state.prioritySort)
  const selectedTypes = useTaskStore((state) => state.selectedTypes)
  const loading = useTaskStore((state) => state.loading)

  const handlePrioritySort = useTaskStore((state) => state.onPrioritySort)
  const handleTypeSelect = useTaskStore((state) => state.onTypeSelect)
  const setShowNewTaskForm = useTaskStore((state) => state.onShowNewTaskForm)
  const loadTasks = useTaskStore((state) => state.loadTasks)
  const renderTasks = useTaskStore((state) => state.renderTasks)
  const clearCompletedTasks = useTaskStore((state) => state.clearCompletedTasks)

  const isPrioritySortActive = useMemo(
    () => prioritySort !== prioritySortOptions[0],
    [prioritySort]
  )

  const completedTasksLen = renderTasks().completedTasks?.length

  // 刷新任务列表
  const handleRefresh = useCallback(() => {
    loadTasks()
  }, [loadTasks])

  // 清空已完成任务
  const handleClearCompleted = useCallback(async () => {
    try {
      await clearCompletedTasks()
    } catch (error) {
      console.error('清空已完成任务失败:', error)
    }
  }, [clearCompletedTasks])

  return (
    <div className="mb-4 pb-4 px-3 shadow-sm">
      {/* 响应式布局容器 */}
      <div className="flex flex-col md:flex-row md:justify-between md:items-center gap-4">
        {/* 左侧：排序和类型筛选 */}
        <div className="flex flex-wrap items-center gap-2">
          {/* 排序和类型筛选 */}
          <div className="flex flex-wrap gap-2">
            <Button
              type={isPrioritySortActive ? 'primary' : 'default'}
              onClick={handlePrioritySort}
              style={{
                backgroundColor: isPrioritySortActive ? 'var(--primary-hover)' : 'var(--bg1)',
                borderColor: 'var(--primary-hover)',
                color: isPrioritySortActive ? '#fff' : 'var(--primary-hover)'
              }}
            >
              {prioritySort === prioritySortOptions[0]
                ? '优先级'
                : prioritySort === 'desc'
                  ? '优先级 ↓'
                  : '优先级 ↑'}
            </Button>
            <div className="hidden md:block w-[2px] h-4 rounded-md bg-primary-hover self-center"></div>
            <Button
              type={selectedTypes.has('all') ? 'primary' : 'default'}
              onClick={() => handleTypeSelect('all')}
              style={{
                backgroundColor: selectedTypes.has('all') ? 'var(--primary)' : 'var(--bg1)',
                borderColor: 'var(--border)',
                color: selectedTypes.has('all') ? '#fff' : 'var(--text2)'
              }}
            >
              全部
            </Button>

            {Object.entries(taskItemTypeConfig).map(([type, config]) => (
              <Button
                key={type}
                type={selectedTypes.has(type as TASK_TYPE) ? 'primary' : 'default'}
                onClick={() => handleTypeSelect(type as TASK_TYPE)}
                style={{
                  backgroundColor: selectedTypes.has(type as TASK_TYPE)
                    ? config.color
                    : 'var(--bg1)',
                  borderColor: config.color,
                  color: selectedTypes.has(type as TASK_TYPE) ? '#fff' : config.color
                }}
              >
                {config.title}
              </Button>
            ))}
          </div>
        </div>

        {/* 右侧：操作按钮 */}
        <div className="flex items-center gap-2 self-end md:self-auto">
          <Tooltip title="刷新待办列表">
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
              loading={loading}
              style={{
                backgroundColor: 'var(--bg1)',
                borderColor: 'var(--border)',
                color: 'var(--text2)'
              }}
            />
          </Tooltip>

          <Tooltip title="清空已完成事项">
            <Button
              icon={<ClearOutlined />}
              onClick={handleClearCompleted}
              disabled={completedTasksLen === 0}
              danger
              style={{
                backgroundColor: completedTasksLen === 0 ? 'var(--disabled)' : 'var(--error)',
                borderColor: completedTasksLen === 0 ? 'var(--border)' : 'var(--error)',
                boxShadow: '0 0 0 0 rgba(0, 0, 0, 0.1)',
                color: completedTasksLen === 0 ? 'var(--text3)' : '#fff'
              }}
            />
          </Tooltip>

          {/* 新增任务按钮 */}
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setShowNewTaskForm(true)}
            style={{
              backgroundColor: 'var(--primary)',
              borderWidth: 0,
              boxShadow: '0 0 0 0 rgba(0, 0, 0, 0.1)',
              color: '#fff'
            }}
          >
            新增任务
          </Button>
        </div>
      </div>
    </div>
  )
}
